<?php

namespace App\Exceptions;

use App\B2BProject\Exception\UserTypeException;
use App\B2BProject\Site\HelperControllerBuildTrait;
use Exception;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Psr\Log\LoggerInterface;

class Handler extends ExceptionHandler
{
    use HelperControllerBuildTrait;

    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport
        = [
            HttpException::class,
            ModelNotFoundException::class,
        ];

    protected $app;

    public function __construct(Application $app, LoggerInterface $log)
    {
        parent::__construct($log);

        $this->app = $app;
    }

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception $e
     *
     * @return void
     */
    public function report(Exception $e)
    {
        return parent::report($e);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Exception               $e
     *
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $e)
    {
        $this->buildModuleVariable();

        if ($e instanceof ModelNotFoundException) {
            // 如果是 ajax 请求则返回指定结构
            if ($request->ajax()) {
                return response()->json(['data' => '不存在的数据'], 404);
            } elseif (isset($this->app['api-request'])) {
                return error_return(900003, 404, '不存在的数据');
            }

            $e = new NotFoundHttpException($e->getMessage(), $e);
        } elseif ($e instanceof UserTypeException) {
            if ($request->ajax()) {
                return response()->json(['data' => '当前的用户类型不具备访问该资源的权限'], 403);
            } elseif (isset($this->app['api-request'])) {
                return error_return(900002, 403, '当前的用户类型不具备访问该资源的权限');
            }

            return response()->view('errors.403', ['exception' => $e], 403);
        } else {
            // 如果是 ajax 请求则返回指定结构
            if ($request->ajax()) {
                return response()->json(['data' => $e->getMessage()], 503);
            } elseif (isset($this->app['api-request'])) {
                return error_return(900000, 503, $e->getMessage());
            }
        }

        return parent::render($request, $e);
    }
}
